import { useEffect, useState } from 'react';
import { Card, Col, Row, message, Button } from 'antd';
import {
    SettingOutlined, PlayCircleOutlined, ExceptionOutlined, LineChartOutlined,
    PauseCircleOutlined, ExclamationCircleOutlined, VerticalAlignBottomOutlined,
} from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { useOutletContext } from 'react-router-dom';

import { startPost, stopPost, getAuto, restart } from '@/api/system';
import { getState } from '@/api/common';
import { downloadBlob } from "@/utils";
import './index.scss';

// 提取常量
const INITIAL_INFO = {
    "ad_serial": "",
    "ipconfig": { "post": "", "ip": "", "cid": "" },
    "cid": "", "ip": "", "post": "", "msg": "",
    "serial_state": "", "state": "", "version": ""
};

function System(props) {
    const { onEvent } = useOutletContext();
    const { t } = useTranslation();
    const [info, setInfo] = useState(INITIAL_INFO);
    const [status, setStatus] = useState("");
    const [loading, setLoading] = useState(false);

    // 提取重复的卡片标题渲染
    const renderCardTitle = (icon, titleKey) => (
        <div className='title'>
            {icon}
            <span className="tit">{t(titleKey)}</span>
        </div>
    );

    // 提取运行状态显示
    const renderRunningStatus = () => {
        if (info.state === 'on') return <div className='txt on'>{t('header.running')}</div>;
        if (info.state === 'off') return <div className='txt off'>{t('header.stopped')}</div>;
        return <div className='txt'>{t('header.unknown')}</div>;
    };

    function getLoad() {
        getState().then(res => {
            setInfo(res[0]);
            onEvent(res[0]);
        });
    }

    function timeFunc() {
        getAuto().then(res => {
            setStatus(res.msg);
        });
        getLoad();
    }

    function start() {
        startPost().then(res => {
            if (info.state === 'on') {
                message.success(t('message.system.running'));
            } else {
                message.success(t('message.system.start'))
            }
            getLoad();
        })
    }

    function stop() {
        stopPost().then(res => {
            message.success(t('message.system.stop'))
            getLoad();
        })
    }

    function reset() {
        restart().then(res => {
            message.success(res.msg)
        })
    }
    useEffect(() => {
        timeFunc();
        const intervalId = setInterval(timeFunc, 2000);
        return () => clearInterval(intervalId);
    }, [])

    return (
        <div className="system-container">
            <div className="row-a1">
                <div className="left">
                    {/* 控制系统 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<SettingOutlined style={{ color: '#08c' }} />, 'system.controlSystem')}>
                            <Row>
                                <Col span={24}>
                                    <div className="start-btn btn" onClick={start}>
                                        <PlayCircleOutlined />
                                        <span>{t('system.startSystem')}</span>
                                    </div>
                                    <div className="pause-btn btn" onClick={stop}>
                                        <PauseCircleOutlined />
                                        <span>{t('system.stopSystem')}</span>
                                    </div>
                                </Col>
                                <Col span={24}>
                                    <div className="reset-btn btn" onClick={reset}>
                                        <PlayCircleOutlined />
                                        <span>{t('system.restartController')}</span>
                                    </div>
                                </Col>
                                <Col span={24}>
                                    <div className="info">
                                        <div className="icon">
                                            <ExclamationCircleOutlined style={{ color: '#0c5460' }} />
                                        </div>
                                        <div className="text">
                                            <div className="txt">
                                                <span className='tit'>{t('system.hint')}:</span>
                                                <span className='in'>{t('system.systemOperationHint')}</span>
                                            </div>
                                        </div>
                                    </div>
                                </Col>
                            </Row>
                        </Card>
                    </div>

                    {/* 日志管理 */}
                    <div className="con-a2">
                        <Card title={renderCardTitle(<ExceptionOutlined style={{ color: '#08c' }} />, 'system.logManagement')}>
                            <Button
                                loading={loading}
                                type="primary"
                                className="download-btn"
                                icon={<VerticalAlignBottomOutlined />}
                                href="/download/"
                            >
                                {t('system.downloadLogs')}
                            </Button>
                        </Card>
                    </div>
                </div>

                <div className="right">
                    <div className="con-a3">
                        <Card title={renderCardTitle(<LineChartOutlined style={{ color: '#08c' }} />, 'system.operationStatistics')}>
                            <div className="list">
                                <div className="li">
                                    <div className="tit">{t('system.systemStatus')}</div>
                                    <div className="text">
                                        <div className={'light ' + info.state}></div>
                                        {renderRunningStatus()}
                                    </div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('system.serverAddress')}</div>
                                    <div className="text">
                                        <div className="txt">{info.ipconfig.ip}</div>
                                    </div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('system.shelfSerialNumber')}</div>
                                    <div className="text">
                                        <div className="txt">{info.ipconfig.cid}</div>
                                    </div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('system.serverConnectionStatus')}</div>
                                    <div className="text">
                                        <div className="txt">{status}</div>
                                    </div>
                                </div>
                            </div>
                        </Card>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default System;